//We Read all Scripts with "DV_RLV_" on start and add the next to the Menu List on Click, also we add an Basic Menu Update and such
list gMenu;
string gMenuPrefix="DV_RLV_";
key ToucherID;
integer gMenuLink =1337;
integer gPage;
integer channel_dialog;
integer listen_id;
Debug(string _text)
{
	llSay(DEBUG_CHANNEL, _text);
}

list pageMenu(list in ,integer page)
{
	list out;
	integer maxpages =llGetListLength(in)/9;
	page = (page)%(maxpages+1);
	out =["<<","Main",">>"];
	integer _listcount =(page *9)+9;
	integer _i=_listcount-9;
	
	for (_i;_i<_listcount;_i++)
	{
		if(_i<=llGetListLength(in)&&llList2String(in,_i)!="")
		out+=llList2String(in,_i);
	}
	return out;
}

makeMenu()
{
	integer _Scripts = llGetInventoryNumber(INVENTORY_SCRIPT); 
    if (_Scripts == 1)
    {
        llOwnerSay ("No other Scripts inside");
    }
    else if (_Scripts > 1)
    {
    	integer i=0;
    	gMenu=[];
    	while(i<_Scripts)
    	{
    		string _Name;
    		_Name= llGetInventoryName(INVENTORY_SCRIPT, i);
    		if(llGetSubString(_Name, 0, llStringLength(gMenuPrefix)-1) ==gMenuPrefix )
    		{
    			gMenu +=llGetSubString(_Name,llStringLength(gMenuPrefix),llStringLength(_Name));
    		}
    		i++; 
    	}
    }
}

displayMenu()
{
	string msg ="Test Menu";
	list _menu;
	//Than we Page ^^ 
	if(llGetListLength(gMenu)<10)
	{
		//Than we Page not ^^
		_menu= [" ","Main", " "]+gMenu;
	}
	else
	{
		//pageing
		_menu= pageMenu(gMenu,gPage);
	}
	channel_dialog = ( -1 * (integer)("0x"+llGetSubString((string)llGetKey(),-5,-1)) );
	listen_id = llListen( channel_dialog, "", NULL_KEY, "");
	llDialog(ToucherID, msg,_menu, channel_dialog);
}

default 
{
    state_entry() 
    {
        makeMenu();
    }
    
    changed(integer change)
    {
    	 if (change & CHANGED_INVENTORY)
    	 { 
    	 	makeMenu();
    	 }  
   	}
   	
    listen(integer channel, string name, key id, string message)
    {
    	llListenRemove(listen_id);
    	if(message=="<<")
  		{
  			gPage--;
			integer maxpages =llGetListLength(gMenu)/9;
			if(gPage<0)
			{
				gPage = maxpages;
			}
			displayMenu();
  		}
  		else if(message==">>")
  		{
  			gPage++;
  			displayMenu();
  		}
    }
    
    link_message(integer sender, integer num, string str, key id)
  	{
  		
  		if(num ==gMenuLink)
  		{
  			if(str==llGetScriptName())
  			{
  				ToucherID=id;
  				displayMenu();
  			}
  		}
  	}
}
